// utils/imageCompress.js
export const compressImageUrl = (url, maxWidth = 1280, maxHeight = 768, quality = 0.6) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "Anonymous"; // 解决跨域问题
    img.onload = () => {
      // 计算缩放比例
      const scale = Math.min(
        maxWidth / img.naturalWidth,
        maxHeight / img.naturalHeight
      );
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      // 设置压缩尺寸
      canvas.width = img.naturalWidth * scale;
      canvas.height = img.naturalHeight * scale;

      // 绘制压缩后的图片
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      // 导出压缩数据
    canvas.toBlob(blob => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result); // 返回 base64 URL
        reader.readAsDataURL(blob);
      }, "image/jpeg", quality);

    };
    img.onerror = (err) => reject(err);
    img.src = url;
  });
};